﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Threading;

namespace FileSplitter
{
    public partial class MainForm : Form
    {
        private volatile bool isCanceled = false;

        public MainForm()
        {
            InitializeComponent();
            isCanceled = false;
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
                txtFile.Text = openFileDialog1.FileName;
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            new Thread(DoTheJob).Start();
        }

        private void DoTheJob()
        {
            var folder = Path.GetDirectoryName(txtFile.Text);
            var fileName = Path.GetFileNameWithoutExtension(txtFile.Text);
            var ext = Path.GetExtension(txtFile.Text);
            int linesToWrite = int.Parse(txtLineCount.Text);
            var file = new StreamReader(txtFile.Text);
            StreamWriter output;

            var lineCount = File.ReadLines(txtFile.Text).Count();

            if(this.InvokeRequired)
               this.Invoke(new MethodInvoker(() => { progressBar1.Maximum = lineCount; }));
            else
                progressBar1.Maximum = lineCount;

            string line;

            int i = 1;
            int currentLines = 0;
            output = new StreamWriter(folder + Path.AltDirectorySeparatorChar + fileName + "-" + i + ext);

            while ((line = file.ReadLine()) != null)
            {
                if (isCanceled)
                    break;

                output.WriteLine(line);
                currentLines++;

                if (currentLines == linesToWrite)
                {
                    currentLines = 0;
                    output.Close();
                    i++;
                    output = new StreamWriter(folder + Path.AltDirectorySeparatorChar + fileName + "-" + i + ext);
                }
                if (this.InvokeRequired)
                    this.Invoke(new MethodInvoker(() => { progressBar1.Value++; }));
                else
                    progressBar1.Value++; 
            }

            output.Close();
            if (this.InvokeRequired)
                this.Invoke(new MethodInvoker(() => { progressBar1.Value = 0; }));
            else
                progressBar1.Value = 0; 

            

            file.Close();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            isCanceled = true;
        }


    }
}
